package service

import (
	"fmt"
	"strings"
	"usplatformserver/internal/model"
	"usplatformserver/pkg/app"
)

// int为0值时，golang默认处理成null，这里OrganType改为*int类型
type PatientListRequest struct {
	OrganType *int   `form:"organType" binding:"required,gte=0"`
	Option    string `form:"option" binding:"max=100"`
	BeginTime string `form:"beginTime"`
	EndTime   string `form:"endTime"`
}

type GetPatientInfoByFileIdRequest struct {
	FileId *int `form:"fileId" binding:"required,gte=0"`
}

func (svc *Service) GetPatientList(param *PatientListRequest, pager *app.Pager) ([]*model.PatientInfo, error) {
	//重组起始时间
	strBegin := reCombinationDateTime(param.BeginTime, "000000")
	//重组结束时间
	strEnd := reCombinationDateTime(param.EndTime, "235959")
	return svc.dao.GetPatientList(*param.OrganType, param.Option, strBegin, strEnd, pager.Page, pager.PageSize)
}

func (svc *Service) CountPatient(param *PatientListRequest) (int, error) {
	//重组起始时间
	strBegin := reCombinationDateTime(param.BeginTime, "000000")
	//重组结束时间
	strEnd := reCombinationDateTime(param.EndTime, "235959")
	return svc.dao.CountPatient(*param.OrganType, param.Option, strBegin, strEnd)
}

func reCombinationDateTime(date, time string) string {
	if date == "" {
		return ""
	}
	//处理日期
	dtTmp := strings.Split(date, "-")
	var strTmp string
	for i := 0; i < len(dtTmp); i++ {
		if i >= 2 {
			strTmp += dtTmp[i]
		} else {
			strTmp += fmt.Sprintf("%02s", dtTmp[i])
		}
	}
	//加上时间
	strTmp += time
	return strTmp
}

// 查询最新患者信息
func (svc *Service) LastPatient() (*model.PatientInfo, error) {
	return svc.dao.LastPatient()
}

func (svc *Service) GetPatientInfoByFileId(fileId int) (*model.PatientInfo, error) {
	return svc.dao.GetPatientInfoByFileId(fileId)
}

func (svc *Service) ListWithoutType(param *PatientListRequest, pager *app.Pager) ([]*model.PatientInfo, error) {
	//重组起始时间
	strBegin := reCombinationDateTime(param.BeginTime, "000000")
	//重组结束时间
	strEnd := reCombinationDateTime(param.EndTime, "235959")
	return svc.dao.GetPatientListWithoutType(param.Option, strBegin, strEnd, pager.Page, pager.PageSize)
}

func (svc *Service) CountWithoutType(param *PatientListRequest) (int, error) {
	//重组起始时间
	strBegin := reCombinationDateTime(param.BeginTime, "000000")
	//重组结束时间
	strEnd := reCombinationDateTime(param.EndTime, "235959")
	return svc.dao.CountPatientWithoutType(param.Option, strBegin, strEnd)
}

func (svc *Service) ListWithoutTypeAndPager(param *PatientListRequest) ([]*model.PatientInfo, error) {
	//重组起始时间
	strBegin := reCombinationDateTime(param.BeginTime, "000000")
	//重组结束时间
	strEnd := reCombinationDateTime(param.EndTime, "235959")
	return svc.dao.GetPatientListWithoutTypeAndPager(param.Option, strBegin, strEnd)
}
